package org.wrigut.scanner;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;

import org.wrigut.scanlib.*;

/* Main.java
 * 
 * Project 1 - CS 3361
 * 
 * Authors: Chris Gutierrez
 *          Jordan Wright
 *          
 * This program takes a file as an input and tokenizes the contents.
 * The tokens are generated according to the Project specification, following
 * the finite automaton provided for the syntax.
 * The switch '-s' treats the next argument as direct string input.
 */

public class Main {

	private static boolean debug = false;
	/**
	 * @param args
	 */
	// This function analyzes the provided arguments and calls
	// the most appropriate subroutine
	public static void main(String[] args) {
		if (args.length < 1) {
			System.out.println("No file specified");
			return;
		}
		if (args[0].equals("-s")) {
			if (args.length == 2) {
				scanString(args[1]);
				return;
			} else {
				System.out.println("No string specified");
				return;
			}
		}
		else if (args.length == 1){
			scanFile(new File(args[0]));
			return;
		}
		System.out.println("Invalid arguments");
	}
	
	//Normal behavior of the program
	private static void scanFile(File f) {
		BufferedReader reader;
		String nl = "\n";
		StringBuilder buffer = new StringBuilder();
		//Check the file
		if (!f.isFile()) {
			System.out.println("Not a file: "+f);
			return;
		}
		//Create the reader
		try {
			reader = new BufferedReader(new FileReader(f));
		} catch (FileNotFoundException e) {
			System.out.println("The file does not exist");
			return;
		}
		//read the first line and setup the loop
		String line;
		try {
			line = reader.readLine();
		} catch (java.io.IOException ex) {
			System.out.println("Error reading file");
			return;
		}
		while (line != null) {
			buffer.append(line);
			buffer.append(nl);
			try {
				line = reader.readLine();
			} catch (java.io.IOException ex) {
				System.out.println("Error reading file");
				return;
			}
		}
		Scanner scanner = new Scanner(buffer.toString());
		scanner.setDebug(debug);
		//done scanning
		ArrayList<Token> tokens = scanner.scanAll();
		//scanning error
		if (tokens == null) {
			System.out.println("Error");
			return;
		}
		printTokens(tokens);
	}
	
	//Called with -s switch
	private static void scanString(String s) {
		Scanner scanner = new Scanner(s);
		scanner.setDebug(debug);
		ArrayList<Token> tokens = scanner.scanAll();
		if (tokens == null) {
			System.out.println("Error");
			return;
		}
		printTokens(tokens);
	}
	
	private static void printTokens(ArrayList<Token> tokens) {
		//nothing to see
		if (tokens.size() <= 1) return;
		for (int i = 0; i < tokens.size()-1; i++) {
			System.out.println(tokens.get(i));
		}
	}
}
